package com.xaicode.locker.JavaSJMS.three.StructureMode.Flyweight;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;

/**
 * 共享元，例举数据库连接池代码
 * @author Locker
 * 	  <br> 2017年5月2日 下午12:22:57
 * @version v1.0
 */
public class ConnectionPool {

	private Vector<Connection> pool;
	
	// 公有属性
	private String url = "jdbc:mysql://localhost:3306/test";  
    private String username = "root";  
    private String password = "root";  
    private String driverClassName = "com.mysql.jdbc.Driver"; 
	
    // 连接池最大连接数
    private int poolSite = 100;
    private static ConnectionPool instance = null;
    Connection conn = null;
    
    private ConnectionPool(){
    	pool = new Vector<Connection>(poolSite);
    	for(int i=0; i<poolSite; i++){
    		try {
    			// 要求JVM查找并加载指定的类，也就是说JVM会执行该类的静态代码段
				Class.forName(driverClassName);
				// 获取连接
				conn = DriverManager.getConnection(url, username, password);
				// 注册连接到连接池
				pool.add(conn);
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    }
    
    // 返回链接到连接池
    public synchronized void close(){
    	pool.add(conn);
    }
    
    // 获取连接池中的一个连接
    public synchronized Connection getConnection(){
    	if(pool.size() > 0){
    		Connection conn = pool.get(0);
    		pool.remove(conn);
    		return conn;
    	}
    	return null;
    }
    
}
